package com.oceansoft.mobile.biz.api.service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.coobird.thumbnailator.Thumbnails;

import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSON;
import com.oceansoft.mobile.biz.api.entity.Dog;
import com.oceansoft.mobile.biz.api.entity.Owner;
import com.oceansoft.mobile.biz.api.entity.OwnerAndDog;
import com.oceansoft.mobile.common.Constant;
import com.oceansoft.mobile.common.dao.ICommonDao;
import com.oceansoft.mobile.common.util.Base64Utils;
import com.oceansoft.mobile.common.util.CacheBaseService;
import com.oceansoft.mobile.common.util.RPCClientUtils;
import com.oceansoft.mobile.common.util.UuidUtils;

@Service
public class ApiOwnerDogServiceImpl implements IApiOwnerDogService {

	

	@Resource
	private ICommonDao commonDao;

	@Override
	public void saveDog(Dog dog) {
		dog.setUid(UuidUtils.getUpperUuid());
		String insertSql = "insert into wx_dog(uid,sexId,typeId,birthday,color,sizeId,lyId,ytId,aqcsId,lyfsId,qzzpstr,myzzpstr,name) values(?,?,?,?,?,?,?,?,?,?,?,?,?)";
		commonDao.update(insertSql, dog.getUid(), dog.getSexId(),
				dog.getTypeId(), dog.getBirthday(), dog.getColor(),
				dog.getSizeId(), dog.getLyId(), dog.getYtId(), dog.getAqcsId(),
				dog.getLyfsId(), dog.getQzzpstr(), dog.getMyzzpstr(),dog.getName());
	}

	@Override
	public void saveOwner(Owner owner) {
		owner.setUid(UuidUtils.getUpperUuid());
		String insertSql = "insert into wx_owner(uid,qzlx,ownername,frxm,xb,zjhm,mz,hjdz,zrrxm,zrrsfzh,lxdh,policeid,sqid,xzdxz,qztxstr,qzsfzzpstr,fczzpstr) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
		commonDao.update(insertSql, owner.getUid(), owner.getQzlx(),
				owner.getOwnername(), owner.getFrxm(), owner.getXb(),
				owner.getZjhm(), owner.getMz(), owner.getHjdz(),
				owner.getZrrxm(), owner.getZrrsfzh(), owner.getLxdh(),
				owner.getPoliceid(), owner.getSqid(), owner.getXzdxz(),
				owner.getQztxstr(), owner.getQzsfzzpstr(), owner.getFczzpstr());
	}

	@Override
	public Dog queryDogById(String id) {
		String sql = "select sexId,typeId,birthday,color,sizeId,lyId,ytId,aqcsId,lyfsId,qzzpstr,myzzpstr,name from wx_dog where uid = ?";
		Dog dog = commonDao.loadOne(sql, new RowMapper<Dog>() {
			@Override
			public Dog mapRow(ResultSet arg0, int arg1) throws SQLException {
				Dog dog = new Dog();
				dog.setSexId(arg0.getString(1));
				dog.setTypeId(arg0.getString(2));
				dog.setBirthday(arg0.getString(3));
				dog.setColor(arg0.getString(4));
				dog.setSizeId(arg0.getString(5));
				dog.setLyId(arg0.getString(6));
				dog.setYtId(arg0.getString(7));
				dog.setAqcsId(arg0.getString(8));
				dog.setLyfsId(arg0.getString(9));
				dog.setQzzpstr(arg0.getString(10));
				dog.setMyzzpstr(arg0.getString(11));
				dog.setName(arg0.getString(12));
				return dog;
			}
		}, id);
		return dog;
	}

	@Override
	public Owner queryOwnerById(String id) {
		String sql = "select qzlx,ownername,frxm,xb,zjhm,mz,hjdz,zrrxm,zrrsfzh,lxdh,policeid,sqid,xzdxz,qztxstr,qzsfzzpstr,fczzpstr from wx_owner where uid = ?";
		Owner owner = commonDao.loadOne(sql, new RowMapper<Owner>() {
			@Override
			public Owner mapRow(ResultSet arg0, int arg1) throws SQLException {
				Owner owner = new Owner();
				owner.setQzlx(arg0.getString(1));
				owner.setOwnername(arg0.getString(2));
				owner.setFrxm(arg0.getString(3));
				owner.setXb(arg0.getString(4));
				owner.setZjhm(arg0.getString(5));
				owner.setMz(arg0.getString(6));
				owner.setHjdz(arg0.getString(7));
				owner.setZrrxm(arg0.getString(8));
				owner.setZrrsfzh(arg0.getString(9));
				owner.setLxdh(arg0.getString(10));
				owner.setPoliceid(arg0.getString(11));
				owner.setSqid(arg0.getString(12));
				owner.setXzdxz(arg0.getString(13));
				owner.setQztxstr(arg0.getString(14));
				owner.setQzsfzzpstr(arg0.getString(15));
				owner.setFczzpstr(arg0.getString(16));
				return owner;
			}
		}, id);
		return owner;
	}

	@Override
	public void deleteDogById(String id) {
		Dog dog=new Dog();
		dog.setUid(id);
		String sql="update wx_dog  set qzzpstr=null,myzzpstr=null where uid = :uid";
		commonDao.updateOne(sql,dog);
	}

	@Override
	public void deleteOwnerById(String id) {
		Owner owner =new Owner();
		owner.setUid(id);
		String sql="update wx_owner set qztxstr=null,qzsfzzpstr=null,fczzpstr=null where uid = :uid";
		commonDao.updateOne(sql,owner);
	}

	@Override
	public String getDept(String key, String deptId) {
		String methodName = "getDeptList";
		String redisKey = "ownerdog:" + key + ":key:" + deptId;
		System.out.println("dog dept =="+redisKey);
		String result = CacheBaseService.getInstance().getObject(redisKey,
				String.class);
		System.out.println("dog dept result =="+result);
		if (StringUtils.isBlank(result)) {
			Object[] obj = RPCClientUtils.getInstance().invoke(Constant.webServiceUrl,
					Constant.namespace, methodName, new Object[] { deptId });
			System.out.println("dog dept obj =="+obj);
			if (obj != null) {
				String rpcResult = obj[0].toString();
				System.out.println("dog dept obj ==" + rpcResult);
				CacheBaseService.getInstance().cache(redisKey, rpcResult,
						5 * 24 * 60 * 60);
				result = rpcResult;
			}
		}
		return result;
	}

	@Override
	public void saveOwner(Owner owner, HttpServletRequest request) {
//		MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
//		MultipartFile multipartFileqztxstr =  multipartHttpServletRequest.getFile("qztxstr1");  //狗主人头像
//		MultipartFile multipartFileqqzsfzzpstr =  multipartHttpServletRequest.getFile("qzsfzzpstr2");  //身份证图片
//		MultipartFile multipartFileqfczzpstr=  multipartHttpServletRequest.getFile("fczzpstr3");  //房产证图片
//		try {
//			InputStream qztxstrStream =  multipartFileqztxstr.getInputStream();
//			InputStream qzsfzzpstrStream =  multipartFileqqzsfzzpstr.getInputStream();
//			InputStream fczzpstrStream =  multipartFileqfczzpstr.getInputStream();
//			long qztxstrLength = multipartFileqztxstr.getSize();
//			long qzsfzzpstrLength= multipartFileqqzsfzzpstr.getSize();
//			long fczzpstrLength= multipartFileqfczzpstr.getSize();
//			System.out.println("qztxstrLength: "+ qztxstrLength);
//			File parentFile = new File("/files/ownerdog");
//			if(!parentFile.exists()){
//				parentFile.mkdirs();
//			}
//			
//			if(qztxstrLength>102400){
//				File qztxstrFile = new File(parentFile,UuidUtils.getUpperUuid()+".jpeg");
//				Thumbnails.of(qztxstrStream).scale(0.25f).toFile(qztxstrFile);   //按照百分之15压缩
//				owner.setQztxstr(Base64Utils.getBase64(qztxstrFile));
//			}else{
//				owner.setQztxstr(Base64Utils.getBase64(qztxstrStream));
//			}
//			if(qzsfzzpstrLength>102400){
//				File qzsfzzpstrFile = new File(parentFile,UuidUtils.getUpperUuid()+".jpeg");
//				Thumbnails.of(qzsfzzpstrStream).scale(0.25f).toFile(qzsfzzpstrFile);   //按照百分之15压缩
//				owner.setQzsfzzpstr(Base64Utils.getBase64(qzsfzzpstrFile));
//			}else{
//				owner.setQzsfzzpstr(Base64Utils.getBase64(qzsfzzpstrStream));
//			}
//			if(fczzpstrLength>102400){
//				File fczzpstrFile = new File(parentFile,UuidUtils.getUpperUuid()+".jpeg");
//				Thumbnails.of(fczzpstrStream).scale(0.25f).toFile(fczzpstrFile);   //按照百分之15压缩
//				owner.setFczzpstr(Base64Utils.getBase64(fczzpstrFile));
//			}else {
//				owner.setFczzpstr(Base64Utils.getBase64(fczzpstrStream));
//			}
			HttpSession session = request.getSession(); 
			/*owner.setQztxstr((String)session.getAttribute("ownerimg1"));
			owner.setQzsfzzpstr((String)session.getAttribute("ownerimg2"));
			owner.setFczzpstr((String)session.getAttribute("ownerimg3"));*/
			this.saveOwner(owner);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
	}

	@Override
	public void saveDog(Dog dog, HttpServletRequest request) {

//		MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
//		MultipartFile multipartFileqzzpstr =  multipartHttpServletRequest.getFile("qzzpstr1");  //狗照片
//		MultipartFile multipartFilemyzzpstr =  multipartHttpServletRequest.getFile("myzzpstr2");  //犬只免疫证照片
//		try {
//			InputStream qzzpstrStream =  multipartFileqzzpstr.getInputStream();
//			InputStream myzzpstrstrStream =  multipartFilemyzzpstr.getInputStream();
//			long qzzpstrLength = multipartFileqzzpstr.getSize();
//			File parentFile = new File("/files/ownerdog");
//			if(!parentFile.exists()){
//				parentFile.mkdirs();
//			}
//			long myzzpstrLength = multipartFilemyzzpstr.getSize();
//			if(qzzpstrLength>102400){
//				File qzzpstrFile = new File(parentFile,UuidUtils.getUpperUuid()+".jpeg");
//				Thumbnails.of(qzzpstrStream).scale(0.25f).toFile(qzzpstrFile);   //按照百分之25压缩
//				dog.setQzzpstr(Base64Utils.getBase64(qzzpstrFile));
//			}else{
//				dog.setQzzpstr(Base64Utils.getBase64(qzzpstrStream));
//			}
//			if(myzzpstrLength>102400){
//				File myzzpstrFile = new File(parentFile,UuidUtils.getUpperUuid()+".jpeg");
//				Thumbnails.of(myzzpstrstrStream).scale(0.25f).toFile(myzzpstrFile);   //按照百分之25压缩
//				dog.setMyzzpstr(Base64Utils.getBase64(myzzpstrFile));
//			}else if(myzzpstrLength>0){
//				dog.setMyzzpstr(Base64Utils.getBase64(myzzpstrstrStream));
//			}
			HttpSession session = request.getSession();
			/*dog.setQzzpstr((String)session.getAttribute("dogimg4"));
			dog.setMyzzpstr((String)session.getAttribute("dogimg5"));*/
			this.saveDog(dog);
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
	}

	@Override
	public String doSubmit(String ownerId, String dogId,HttpServletRequest request) {
		String rpcResult = null;
		 Owner owener = this.queryOwnerById(ownerId);
		 owener.setFczzpstr((String)request.getSession().getAttribute("ownerimg3"));
		 owener.setQzsfzzpstr((String)request.getSession().getAttribute("ownerimg2"));
		 owener.setQztxstr((String)request.getSession().getAttribute("ownerimg1"));
		 owener.setPmzpstr((String)request.getSession().getAttribute("ownerimg4"));
		 owener.setQszpstr((String)request.getSession().getAttribute("ownerimg5"));
		 Dog dog = this.queryDogById(dogId);
		 dog.setQzzpstr((String)request.getSession().getAttribute("dogimg4"));
		 dog.setMyzzpstr((String)request.getSession().getAttribute("dogimg5"));
		 OwnerAndDog ownerAndDog = new OwnerAndDog();	
		 ownerAndDog.setDog(dog);
		 ownerAndDog.setOwner(owener);
		 String rpcJson = JSON.toJSONString(ownerAndDog);
		 Object[] rcpResultObj = RPCClientUtils.getInstance().invoke(Constant.webServiceUrl,
					Constant.namespace, "saveDogInfo", new Object[] {rpcJson });
		 if(rcpResultObj != null){
			 rpcResult = rcpResultObj[0].toString();
		 }
		/*this.deleteDogById(dogId);
		this.deleteOwnerById(ownerId);*/
		 return  rpcResult;
	}

	@Override
	public String getDogLx() {
	 
		String redisKey = "ownerdog:doglx";
		String result = CacheBaseService.getInstance().getObject(redisKey,
				String.class);
		if(StringUtils.isBlank(result)){
			String sql = "select id,name from wx_doglx";
			List<Map<String, Object>> list = commonDao.loadMapList(sql);
			String dbResult = JSON.toJSONString(list);
			result = dbResult;
			CacheBaseService.getInstance().cache(redisKey, dbResult,30*24*60*60);
		}
		return result;
	}

	@Override
	public String getCountry() {
		String redisKey = "ownerdog:country";
		String result = CacheBaseService.getInstance().getObject(redisKey,
				String.class);
		if(StringUtils.isBlank(result)){
			String sql = "select id,name,slc from wx_country order by slc desc";
			List<Map<String, Object>> list = commonDao.loadMapList(sql);
			String dbResult = JSON.toJSONString(list);
			result = dbResult;
			CacheBaseService.getInstance().cache(redisKey, dbResult,30*24*60*60);
		}
		return result;
	}

	@Override
	public List<Dog> getDogProcessList(String zjhm) {
		List<Dog> dogs = null;
		String redisKey = "ownerdog:dogprocess:list:"+zjhm;
		String result = CacheBaseService.getInstance().getObject(redisKey,
				String.class);
		String rpcMethod="getProgressInfo";
		if(StringUtils.isBlank(result)){
			Object[] rpcResultObject = RPCClientUtils.getInstance().invoke(Constant.webServiceUrl, Constant.namespace, rpcMethod, new Object[]{zjhm});
			if(null != rpcResultObject){
				String rpcResultStr= rpcResultObject[0].toString();
				if(!"0".equals(rpcResultStr)){
					CacheBaseService.getInstance().cache(redisKey, rpcResultStr,30*60);
					dogs = JSON.parseArray(rpcResultStr, Dog.class);
				}
				
			}
		}else{
			dogs = JSON.parseArray(result, Dog.class);
		}
		return dogs;
	}

	@Override
	public Dog getDogProcessDetail(String dogId) {
		Dog dog = null;
		OwnerAndDog ownerAndDog = null;
		String redisKey = "ownerdog:dogprocess:detail:"+dogId;
		String result = CacheBaseService.getInstance().getObject(redisKey,
				String.class);
		String rpcMethod = "getDogInfoFromId";
		if(StringUtils.isBlank(result)){
			Object[] rpcResultObject = RPCClientUtils.getInstance().invoke(Constant.webServiceUrl, Constant.namespace, rpcMethod, new Object[]{dogId});
			if(null != rpcResultObject){
				String rpcResultStr= rpcResultObject[0].toString();
				CacheBaseService.getInstance().cache(redisKey, rpcResultStr,30*60);
				ownerAndDog = JSON.parseObject(rpcResultStr, OwnerAndDog.class);
			}
		}else{
			ownerAndDog = JSON.parseObject(result, OwnerAndDog.class);
		}
		return ownerAndDog.getDog();
	}

	@Override
	public String getQz(String id) {
		String redisKey = "ownerdog:doglx:"+id;
		String result = CacheBaseService.getInstance().get(redisKey);
		if(StringUtils.isBlank(result)){
			String sql = "select name from wx_doglx where id = ? ";
			String dbResult = commonDao.getStringColumn(sql, id);
			result = dbResult;
			CacheBaseService.getInstance().cache(redisKey, dbResult,30*24*60*60);
		}
		return result;
	}

	@Override
	public String getZxdtList(String pageIndex, String pageSize) {
		String rpcMethod = "getZxdtList";
		String redisKey = "ownerdog:zxdt:"+pageIndex+":"+pageSize;
		String result = CacheBaseService.getInstance().get(redisKey);
		if(StringUtils.isBlank(result)){
			Object[] rpcResultObject = RPCClientUtils.getInstance().invoke(Constant.webServiceUrl, Constant.namespace, rpcMethod, new Object[]{pageIndex,pageSize});
			if(null != rpcResultObject){
				String rpcResultStr= rpcResultObject[0].toString();
				CacheBaseService.getInstance().cache(redisKey, rpcResultStr,30*60);
				result = rpcResultStr;
			}
		}
		return result;
	}

	@Override
	public String getZxdtInfo(String id) {
		String rpcMethod = "getZxdtInfo";
		String redisKey = "ownerdog:zxdt:"+id;
		String result = CacheBaseService.getInstance().get(redisKey);
		if(StringUtils.isBlank(result)){
			Object[] rpcResultObject = RPCClientUtils.getInstance().invoke(Constant.webServiceUrl, Constant.namespace, rpcMethod, new Object[]{id});
			if(null != rpcResultObject){
				String rpcResultStr= rpcResultObject[0].toString();
				CacheBaseService.getInstance().cache(redisKey, rpcResultStr,30*60);
				result = rpcResultStr;
			}
		}
		return result;
	}
	
	
	
	

}
